package model.requirement6;

import model.DatabaseConnection;
import model.MenuItem;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class CentralMenuDAO {
    // 查询中央菜单
    public List<MenuItem> getCentralMenu() throws Exception {
        List<MenuItem> items = new ArrayList<>();
        try (Connection connection = DatabaseConnection.getConnection()) {
            String query = "SELECT * FROM CentralMenu";
            PreparedStatement statement = connection.prepareStatement(query);
            ResultSet resultSet = statement.executeQuery();

            while (resultSet.next()) {
                items.add(new MenuItem(
                        resultSet.getInt("ItemID"),
                        0, // StoreID 不适用
                        resultSet.getString("ItemName"),
                        resultSet.getString("ItemType"),
                        resultSet.getDouble("Price")
                ));
            }
        }
        return items;
    }

    // 按类型查询菜单
    public List<MenuItem> getMenuByType(String itemType) throws Exception {
        List<MenuItem> items = new ArrayList<>();
        try (Connection connection = DatabaseConnection.getConnection()) {
            String query = "SELECT * FROM CentralMenu WHERE ItemType = ?";
            PreparedStatement statement = connection.prepareStatement(query);
            statement.setString(1, itemType);
            ResultSet resultSet = statement.executeQuery();

            while (resultSet.next()) {
                items.add(new MenuItem(
                        resultSet.getInt("ItemID"),
                        0, // StoreID 不适用
                        resultSet.getString("ItemName"),
                        resultSet.getString("ItemType"),
                        resultSet.getDouble("Price")
                ));
            }
        }
        return items;
    }

    // 添加新的餐点
    public void addMenuItem(String name, String type, double price) throws Exception {
        try (Connection connection = DatabaseConnection.getConnection()) {
            String query = "INSERT INTO CentralMenu (ItemName, ItemType, Price) VALUES (?, ?, ?)";
            PreparedStatement statement = connection.prepareStatement(query);
            statement.setString(1, name);
            statement.setString(2, type);
            statement.setDouble(3, price);
            statement.executeUpdate();
        }
    }

    // 更新中央菜单价格
    public void updatePrice(int itemID, double newPrice) throws Exception {
        try (Connection connection = DatabaseConnection.getConnection()) {
            String query = "UPDATE CentralMenu SET Price = ? WHERE ItemID = ?";
            PreparedStatement statement = connection.prepareStatement(query);
            statement.setDouble(1, newPrice);
            statement.setInt(2, itemID);
            statement.executeUpdate();
        }
    }
}
